package com.sysware.mymodule.service;

import com.sysware.mymodule.entity.DataObject;
import com.sysware.mymodule.repository.DataObjectRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.Date;

@Service
@Transactional
public class DataObjectServiceImpl implements DataObjectService {

    @Resource
    DataObjectRepository dataObjectRepository;

    @Override
    public void insert(String name, String desc) {
        DataObject dataObject = new DataObject();
        dataObject.setName(name);
        dataObject.setDescription(desc);
        dataObject.setCreateTime(new Date());
        dataObject.setDoubleValue(new BigDecimal("99999999999999"));
        dataObject.setCreator("user1111");
        dataObjectRepository.save(dataObject);
    }

    @Override
    public int update(String id, String name) {
        return 0;
    }

    @Override
    public int delete(String[] ids) {
        return 0;
    }

    @Override
    public DataObject getDataObject(String id) {
        return dataObjectRepository.findById(id).get();
    }

    @Override
    public Page<DataObject> getDataObjectByPage(String name, int start, int limit) {
        Sort sort = new Sort(Sort.Direction.DESC,"id"); //创建时间降序排序
        Pageable pageable = PageRequest.of(start,limit,sort);
        Page<DataObject> dataObjectPage = dataObjectRepository.findByNameLike(name+"%", pageable);
        if(dataObjectPage.isEmpty()){
            dataObjectPage = dataObjectRepository.findAll(pageable);
        }
        return dataObjectPage;
    }
}
